package com.jiyun.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.jiyun.pojo.goods.Admin;
import com.jiyun.pojo.goods.Role;
import com.jiyun.service.goods.AdminService;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class SpringSecurityService implements UserDetailsService {

    @Reference
    AdminService adminService;


    // 加载用户信息，通过用户名
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户信息，通过用户名
        Admin admin = adminService.findByUsername(username);
        String password = "{noop}"+admin.getPassword();

        // 将用户的角色信息，放入到list集合中
        List<SimpleGrantedAuthority> list = new ArrayList<>();
        Set<Role> roles = admin.getRoles();
        for (Role role : roles) {
            list.add(new SimpleGrantedAuthority(role.getKeyword()));
        }

        // 最终构建出，security框架所需要的用户信息
        return new User(username,password,list);
    }
}
